<template>
  <div>
    <div v-if="view">
      <slot name="view">
        <el-tag v-for="(o,i) in value"
                :key="i"
                :type="orgTypeColorMap[1]"
                closable
                class="inline-block m5"
                @close="remove(i)"
              >{{ o.realName }}</el-tag>
      </slot>
    </div>
    <span @click="showUserTag=true">
      <slot name="choose">
        <el-button size="small" icon="el-icon-plus">选择</el-button>
      </slot>
    </span>
    
    <el-button v-show="showClear && value.length > 1" size="small" icon="el-icon-close" @click="value = []">清空</el-button>
    <el-dialog
      title="选择用户"
      :visible.sync="showUserTag"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="800px"
      @open="openTag"
    >
      <component :is="userTag" ref="tag" :multi="multi"/>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="addUser">保 存</el-button>
        <el-button size="small" @click="showUserTag = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Mixin } from '@/utils/mixin'
export default {
  name: 'UserView',
  mixins: [Mixin],
  components: {},
  props: {
    value: {
      type: Array,
      default: ()=> []
    },
    view: {
      type: Boolean,
      default: true
    },
    multi: {
      type: Boolean,
      default: true
    },
    showClear: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      showUserTag: false,
    }
  },
  computed: {
    userTag() {
      return require('/src/components/tag/user-tag').default
    },
  },
  mounted() {

  },
  methods: {
    addUser() {
      const p = this.$refs.tag.get()
      if (p.length === 0) {
        this.$message.warning('请选择用户')
        return
      }
      // 去重
      const ids = []
      if(!this.multi){
        this.value.splice(0,this.value.length)
      }
      let parent = this.value
      // debugger
      for (let i = 0; i < parent.length; i++) {
        ids.push(parent[i].userId)
      }
      for (let i = 0; i < p.length; i++) {
        if (ids.indexOf(p[i].userId) === -1) {
          parent.push(p[i])
          ids.push(p[i].userId)
        }
      }
      this.showUserTag = false
      console.log('addUser',parent,ids,p);
      this.$nextTick(()=>{
        this.$emit('addTag',parent,ids)
      })
    },
    openTag() {
      this.$nextTick(() => {
        this.$refs.tag.clear()
        this.$refs.tag.query()
      })
    },
    show() {
      this.showUserTag = true
    },
    close() {
      this.showUserTag = false
    },
    remove(i){
      this.value.splice(i, 1)
      this.$emit('remove',i)
    },
    clear() {
      //this.value = []
    }
  }
}
</script>
<style scoped>

</style>
